Latest update: March 2015
In this tutorial, we’ll cover uploading a file to an FTP server. We’ll put together a simple script that, when run, uploads all files in a directory. It should also log what it’s doing to a file. Note: If your FlashAir card is currently mounted on a PC, it may be unable to write the log file.
First, fill out some of the variables we are going to use. You’ll need to use your server’s info.
local logfile = "/FTPLog.txt" -- Where to log output on the FA
local folder = "/Upload" -- What folder to upload files from
local server = "192.168.1.1" -- The FTP server's IP
local serverDir = "/" -- The path on the FTP server to use.
local user = "ftp" -- FTP username
local passwd = "abc123" -- FTP passwd
Next, we should assemble our variables into a convenient URL we’ll use to upload.
-- Assemble our FTP command string
-- example: "ftp://user:pass@192.168.1.1/"
local ftpstring = "ftp://"..user..":"..passwd.."@"..server..serverDir
Then create the log file…
-- Open the log file
local outfile = io.open(logfile, "w")
-- Write a header
outfile:write("File list: \n")
Remember to close it at the end!
--Close our log file
outfile:close()
Ok, we’re ready to start! We’ll be using LuaFileSystem (lfs) to scan the upload directory, and the fa.ftp to perform the upload itself. The results are output to the log file - although some output will also be displayed if you run the script from your web browser.
-- For each file in folder...
for file in lfs.dir(folder) do
-- Get that file's attributes
attr = lfs.attributes(folder .. "/" .. file)
print( "Found "..attr.mode..": " .. file )
-- Don't worry about directories (yet)
if attr.mode == "file" then
--Attempt to upload the file!
--ex ftp("put", "ftp://user:pass@192.168.1.1/test.jpg", "Upload/test.jpg")
response = fa.ftp("put", ftpstring..file, folder .. "/" .. file)
--Check to see if it worked, and log the result!
if response ~= nil then
print("Success!")
outfile:write("" .. file .. "... Success!\n")
else
print("Fail :(")
outfile:write("" .. file .. "...Fail :(\n")
end
end
end
That’s it! Pretty easy eh?
All sample code on this page is licensed under BSD 2-Clause License